#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
#include <sstream>
#include <memory>

bool serialize(const Json::Value &val, std::string &body)
{
    std::stringstream ss;
    //先实例化一个工厂类对象
    Json::StreamWriterBuilder swb;
    //通过工厂类对象来生产派生类对象
    std::unique_ptr<Json::StreamWriter> w(swb.newStreamWriter());
    bool ret = w->write(val, &ss);
    if(ret != 0)
    {
        return false;
    }

    body = ss.str();
    return true;
}

bool deserialize(const std::string &body, Json::Value &val)
{
    Json::CharReaderBuilder crb;
    std::unique_ptr<Json::CharReader> r(crb.newCharReader());

    std::string errs;
    bool ret = r->parse(body.c_str(), body.c_str() + body.size(), &val, &errs);
    if (ret == false) 
    {
        std::cout << "json unserialize failed : " << errs << std::endl;
        return false;
    }

    return true;
}

int main()
{
    const char* sex = "男";
    const char* name = "小明";
    int age = 18;
    int score[4] = {70, 80, 90};

    Json::Value stu1;
    stu1["姓名"] = name;
    stu1["性别"] = sex;
    stu1["年龄"] = age;
    stu1["分数"].append(score[0]);
    stu1["分数"].append(score[1]);
    stu1["分数"].append(score[2]);
    Json::Value fav;
    fav["书籍"] = "西游记";
    fav["运动"] = "打篮球";
    stu1["爱好"] = fav;
    std::string body;

    bool ret1 = serialize(stu1, body);
    std::cout << body << std::endl;

    std::string str = R"({"姓名":"小黑", "年龄": 19, "成绩":[32, 45, 56]})";
    Json::Value stu2;
    bool ret2 = deserialize(str, stu2);
    if (ret2 == false) 
    {
        return -1;
    }

    std::cout << std::endl;
    std::cout << "姓名: " <<  stu2["姓名"].asString() << std::endl;
    std::cout << "年龄: " <<  stu2["年龄"].asInt() << std::endl;
    int sz = stu2["成绩"].size();
    for (int i = 0; i < sz; i++) 
    {
        std::cout << "成绩: " <<  stu2["成绩"][i].asFloat() << std::endl;
    }

    return 0;
}
